import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import "./Community.css"
import { listPostsService, fetchPinnedPostService } from "../api/CommunityApi"

function Community(){
  const [posts, setPosts] = useState([]);
  const [pinnedPosts, setPinnedPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const forums = [
    {id: 1, name: "动漫"},
    {id: 2, name: "面经"},
    {id: 3, name: "游戏"},
    {id: 4, name: "其它"}
  ];
  const types = [
    { id: 1, name: "普通" },
    { id: 2, name: "精华" },
    { id: 3, name: "悬赏" }
  ];
  const status = [
    { id: 1, name: "正常" },
    { id: 2, name: "审核中" },
    { id: 3, name: "已锁定" }
  ]

  const timeRanges = [
    { value: "", label: "全部" },
    { value: "day", label: "一天内" },
    { value: "week", label: "一周内" },
    { value: "month", label: "一个月内" }
  ];

  const sortOptions = [
    { value: "createdTime", label: "按时间排序" },
    { value: "commentCount", label: "按评论数排序" },
    { value: "viewCount", label: "按浏览数排序" }
  ];

  const pageSizeOptions = [10, 20, 50];

  const [searchData, setSearchData] = useState({
    forumIds: [1,2,3,4], // 改为数组支持多选
    keyword: "",
    author: "",
    type: '', // 不传：全部，1: 普通, 2: 精华, 3: 悬赏
    timeRange: "", //不传：全部，day week month
    sortBy: "createdTime", // createdTime, commentCount, viewCount
    isHot: false, // 是否只显示热门帖子
    page: 1, // 当前页码
    pageSize: 10, // 每页显示数量
  })

  const fetchPosts = async () => {
    setLoading(true)
    try {
      const response = await listPostsService(searchData);
      if (response.status !== 200) {
        console.error("获取帖子失败:", response.statusText)
      } else {
        setPosts(response.data.postList || [])
        setPagination({
          current: searchData.page || 1,
          pageSize: searchData.pageSize || 10,
          total: response.data.total || 0,
        });
      }
    } catch (error) {
      console.error("获取帖子失败:", error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    let isMounted = true;
    const fetchAllPinned = async () => {
      const allPinned = [];
      for (const forumId of searchData.forumIds) {
        try {
          const res = await fetchPinnedPostService(forumId);
          if (res && res.data && Array.isArray(res.data)) {
            // 兼容接口返回数组或单个对象
            res.data.forEach(post => {
              if (!allPinned.find(p => p.id === post.id)) {
                allPinned.push(post);
              }
            });
          } else if (res && res.data && res.data.id) {
            if (!allPinned.find(p => p.id === res.data.id)) {
              allPinned.push(res.data);
            }
          }
        } catch {}
      }
      if (isMounted) setPinnedPosts(allPinned);
    };
    fetchAllPinned();
    return () => { isMounted = false; };
  }, [searchData.forumIds]);

  useEffect(() => {
    fetchPosts();
  }, [searchData]);

  const handleForumChange = (forumId) => {
    setSearchData((prev) => {
      const newForumIds = prev.forumIds.includes(forumId)
        ? prev.forumIds.filter(id => id !== forumId)
        : [...prev.forumIds, forumId];
      return {
        ...prev,
        forumIds: newForumIds,
        page: 1 // 重置页码
      };
    });
  };

  const handleSearch = () => {
    setPagination((prev) => ({
      ...prev,
      current: 1 // 重置页码
    }));
    fetchPosts();
  };

  const handleReset = () => {
    setSearchData({
      forumIds: [1,2,3,4], 
      keyword: "",
      author: "",
      type: '', 
      timeRange: "", 
      sortBy: "createdTime", 
      isHot: false,
      page: 1,
      pageSize: 10,
    })
  };
  const handlePageChange = (page) => {
    setSearchData((prev) => ({
      ...prev,
      page: page,
    }));
  }

  const handlePageSizeChange = (pageSize) => {
    setSearchData((prev) => ({
      ...prev,
      pageSize: pageSize,
      page: 1, // 重置页码
    }));
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString)
    return date.toLocaleString("zh-CN")
  }

  const renderPagination = () => {
    const totalPages = Math.ceil(pagination.total / pagination.pageSize);
    const pages = [];

    let startPage = Math.max(1, pagination.current - 2);
    let endPage = Math.min(totalPages, pagination.current + 2);

    if(endPage - startPage < 4) {
      if(startPage === 1) {
        endPage = Math.min(totalPages, startPage + 4);
      } else if(endPage === totalPages) {
        startPage = Math.max(1, endPage - 4);
      }
    }

    if(startPage > 1) {
      pages.push(
        <button key="1" className="page-btn" onClick={() => handlePageChange(1)}>
          1
        </button>,
      );
      if(startPage > 2) {
        pages.push(
          <span key="start-ellipsis" className="page-ellipsis">
            ...
          </span>,
        )
      }
    }

    // 中间页码
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          className={`page-btn ${pagination.current === i ? "active" : ""}`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>,
      )
    }

    // 末页
    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        pages.push(
          <span key="end-ellipsis" className="page-ellipsis">
            ...
          </span>,
        )
      }
      pages.push(
        <button key={totalPages} className="page-btn" onClick={() => handlePageChange(totalPages)}>
          {totalPages}
        </button>,
      )
    }
    return pages;      
  }
  return (
    <div className="forum-page">
      <div className="forum-header-wrapper">
        <h1 className="forum-title">社区论坛</h1>
        <div className="new-thread-btn-wrapper">
          <button className="new-thread-btn" onClick={() => navigate("/community/new")}>
            +
          </button>
        </div>
      </div>

      {/* 查询表单 */}
      <div className="search-form">
        <div className="search-grid">
          {/* 板块选择 */}
          <div className="search-item">
            <label className="search-label">板块：</label>
            <div className="multi-select-container">
              <div className="checkbox-group">
                {forums.map((forum) => (
                  <label key={forum.id} className="checkbox-item">
                    <input
                      type="checkbox"
                      checked={searchData.forumIds.includes(forum.id)}
                      onChange={() => handleForumChange(forum.id)}
                    />
                    <span className="checkbox-text">{forum.name}</span>
                  </label>
                ))}
              </div>
              { searchData.forumIds.length > 0 && (
               <div className="selected-tags">
                {searchData.forumIds.map((id) => {
                  const forum = forums.find(f => f.id === id);
                  return (
                    <span key={id} className="selected-tag">
                      {forum.name}
                      <button type="button" onClick={() => handleForumChange(id)} className="remove-tag">
                        ×
                      </button>
                    </span>
                  );
                })}
               </div>
              )}
            </div>
          </div>

          {/* 关键词搜索 */}
          <div className="search-item">
            <label className="search-label">关键词：</label>
            <input
              type="text"
              placeholder="请输入关键词"
              value={searchData.keyword}
              onChange={(e) => setSearchData({ ...searchData, keyword: e.target.value })}
              className="search-input"
            />
          </div>

          {/* 作者搜索 */}
          <div className="search-item">
              <label className="search-label">作者：</label>
              <input
              type="text"
              placeholder="请输入作者昵称"
              value={searchData.author}
              onChange={(e) => setSearchData({ ...searchData, author: e.target.value })}
              className="search-input"
              />
          </div>

        {/* 帖子类型 */}
          <div className="search-item">
            <label className="search-label">帖子类型：</label>
            <select
              value={searchData.type}
              onChange={(e) => setSearchData({ ...searchData, type: e.target.value })}
              className="search-select"
            >
            <option value="">全部</option>
            {types.map((type) => (
              <option key={type.id} value={type.id}>
              {type.name}
              </option>
            ))}
            </select>
          </div>

          {/* 时间范围 */}
          <div className="search-item">
            <label className="search-label">时间范围：</label>
            <select
              value={searchData.timeRange}
              onChange={(e) => setSearchData({ ...searchData, timeRange: e.target.value })}
              className="search-select"
            >
              {timeRanges.map((range) => (
                <option key={range.value} value={range.value}>
                  {range.label}
                </option>
              ))}
            </select>
          </div>

          {/* 排序方式 */}
          <div className="search-item">
            <label className="search-label">排序方式：</label>
            <select
              value={searchData.sortBy}
              onChange={(e) => setSearchData({ ...searchData, sortBy: e.target.value })}
              className="search-select"
            >
              {sortOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
            
          {/* 热门帖子 */}
          <div className="search-item checkbox-only">
            <label className="checkbox-item hot-checkbox">
              <input
                type="checkbox"
                checked={searchData.isHot}
                onChange={(e) => setSearchData({ ...searchData, isHot: e.target.checked })}
              />
              <span className="checkbox-text">仅显示热门帖</span>
            </label>
          </div>

          {/* 操作按钮 */}
          <div className="search-item search-actions">
            <button className="search-btn" onClick={handleSearch}>
              🔍 搜索
            </button>
            <button className="reset-btn" onClick={handleReset}>
              🔄 重置
            </button>
          </div>
        </div>
      </div>

      {/* 置顶帖子列表 */}
    {pinnedPosts && pinnedPosts.length > 0 && (
      <div className="forum-content" style={{ marginBottom: 0 }}>
        <div className="content-header">
          <h2>置顶帖子</h2>
        </div>
        {pinnedPosts.map((post) => (
          <div
            key={post.id}
            className="thread-card"
            style={{
              borderLeft: "4px solid #ff6699",
              background: "#fff7fa",
              marginBottom: 12,
            }}
            onClick={() => navigate(`/community/${post.id}`)}
          >
            <div className="thread-header">
              <h4 className="thread-title">
                <span className="pinned-tag">置顶</span>
                <span className={`type-tag type-${post.type}`}>{types.find(t => t.id === post.type)?.name}</span>
                {post.title}
              </h4>
            </div>
            <div className="thread-meta">
              <span>作者：{post.userName}</span>
              <span>发布时间：{formatDate(post.createdTime)}</span>
              <span>回复：{post.commentCount}</span>
              <span>点击：{post.viewCount}</span>
              <span>点赞：{post.likeCount}</span>
            </div>
          </div>
        ))}
      </div>
    )}

      <div className="forum-content">
        <div className="content-header">
          <h2>帖子列表</h2>
          <div className="result-info">共找到 {pagination.total} 条结果</div>
        </div>

        { loading ? (
          <div className="loading">加载中...</div>
        ) : (
          <>
            { posts.length === 0 ? (
              <div className="no-data">暂无数据</div>
            ) : (
              posts.map((post) => (
                <div key={post.id} className="thread-card" onClick={() => navigate(`/community/${post.id}`)}>
                  <div className="thread-header">
                    <h4 className="thread-title">
                      {post.isPinned === 1 && <span className="pinned-tag">置顶</span>}
                      <span className={`type-tag type-${post.type}`}>{types.find(t => t.id === post.type ).name}</span>
                      <span className={`status-badge status-${post.status}`}>{status.find(s => s.id === post.status)?.name}</span>
                      {post.title}
                    </h4>
                  </div>
                <div className="thread-meta">
                  <span>作者：{post.userName}</span>
                  <span>发布时间：{formatDate(post.createdTime)}</span>
                  <span>回复：{post.commentCount}</span>
                  <span>点击：{post.viewCount}</span>
                  <span>点赞：{post.likeCount}</span>
                </div>
              </div>
              ))
            )}
          </>
        )}

        {/* 分页 */}
        {pagination.total > 0 && (
          <div className="pagination-wrapper">
            <div className="pagination-info">
              <span>每页显示：</span>
              <select
                value={pagination.pageSize}
                onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                className="page-size-select"
              >
                {pageSizeOptions.map((size) => (
                  <option key={size} value={size}>
                    {size} 条
                  </option>
                ))}
              </select>
            </div>

            <div className="pagination">
              <button
                className="page-btn"
                disabled={pagination.current === 1}
                onClick={() => handlePageChange(pagination.current - 1)}
              >
                上一页
              </button>

              {renderPagination()}

              <button
                className="page-btn"
                disabled={pagination.current === Math.ceil(pagination.total / pagination.pageSize)}
                onClick={() => handlePageChange(pagination.current + 1)}
              >
                下一页
              </button>
            </div>

            <div className="pagination-info">
              第 {pagination.current} 页，共 {Math.ceil(pagination.total / pagination.pageSize)} 页
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default Community;